/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.aal.business;

import java.security.MessageDigest;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
import java.util.regex.*;
/**
 *
 * @author quy
 */
public class PasswordInterceptor {
    public PasswordInterceptor(){}
    
     private String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
     private String PHONE_REGEX = "^\\d*$";
    @AroundInvoke
    public Object give(InvocationContext ic) throws Exception
    {
        if(ic.getMethod().getName().equals("createCustomer") || ic.getMethod().getName().equals("editCustomer"))
        {
            Object[] params = ic.getParameters();
            params[1] = md5((String)params[1]);
            params[5] = Regemail((String)params[5]);
            params[6] = Regphone((String)params[6]);
            ic.setParameters(params);
        }
        if(ic.getMethod().getName().equals("loginOk")){
            Object[] params = ic.getParameters();
            params[1] = md5((String)params[1]);
            ic.setParameters(params);
        }
        else if(ic.getMethod().getName().equals("createUser") || ic.getMethod().getName().equals("editUser")){
            Object[] params = ic.getParameters();
            params[1] = md5((String)params[1]);
            ic.setParameters(params);
        }
        return ic.proceed();
    }
    private String Regemail(String email){
        if(email.matches(EMAIL_REGEX)){
            return email;
        }
        else{
            return "wrong email";
        }
    }
    private String Regphone(String phone){
        if(phone.matches(PHONE_REGEX)){
            return phone;
        }
        else{
            return "0";
        }
    }
    private String md5(String pwd) {
        StringBuilder password = null;
        try {
            MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(pwd.getBytes());
            password = new StringBuilder();
            for (int i = 0; i < array.length; ++i) {
                password.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
            }
        } catch (java.security.NoSuchAlgorithmException e) {
        }
        return password.toString();
    }
}
